/*
 * Copyright (c) Jack魏 2024 - 2024, All Rights Reserved.
 */

package cn.jackwei.yiyi.service.sys;

import cn.jackwei.yiyi.mapper.SysPageMapper;
import cn.jackwei.yiyi.pojo.bean.SysPage;
import cn.jackwei.yiyi.pojo.model.SysPageModel;
import cn.jackwei.yiyi.pojo.query.SysPageQuery;
import cn.jackwei.yiyi.util.Result;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 页面表Service类
 *
 * @author Jack魏
 * @since 2024-07-21
 */
@Slf4j
@Service
public class SysPageService extends ServiceImpl<SysPageMapper, SysPage> {
    @Autowired
    private SysPageMapper sysPageMapper;

    /**
     * 根据条件分页查询页面表
     *
     * @param query 条件
     * @return 查询列表
     */
    public Page<SysPageModel> pageSysPage(SysPageQuery query) {
        return sysPageMapper.pageSysPage(query);
    }

    /**
     * 查询所有页面列表（不分页树形结构）
     *
     * @return 查询列表
     */
    public Result<List<SysPage>> listPageTree() {
        LambdaQueryWrapper<SysPage> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysPage::getParentId, 0)
                .or()
                .isNull(SysPage::getParentId)
                .orderByAsc(SysPage::getSort);
        List<SysPage> pageList = baseMapper.selectList(wrapper);
        if (pageList != null && pageList.size() > 0) {
            pageList.forEach(this::listAllChild);
        }
        return Result.success(pageList);
    }

    /**
     * 递归查询所有子页面
     *
     * @param sysPage 父页面信息
     */
    private void listAllChild(SysPage sysPage) {
        LambdaQueryWrapper<SysPage> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysPage::getParentId, sysPage.getId())
                .orderByAsc(SysPage::getSort);
        List<SysPage> pageList = baseMapper.selectList(wrapper);
        sysPage.setChildren(pageList);
        if (pageList != null && pageList.size() > 0) {
            pageList.forEach(this::listAllChild);
        }
    }

}